import { AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { ActionReducerMapBuilder } from '@reduxjs/toolkit';
import { addPatientAPI, deletePatientAPI, fetchPatientListAPI, findPatientAPI, updatePatientAPI } from '@/API/patientAPI';
import { Patient } from '@/type/PatientType';
import { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';


type InitialState = {
  patientList: Patient[]
}

const initialState: InitialState = {
  patientList: [],
};


/**
 * @description 获取就诊人列表的异步函数
 * */
export const fetchPatientList: AsyncThunk<Patient[], void, AsyncThunkConfig> = createAsyncThunk('fetchPatientList', async (_: void, { rejectWithValue }) => {
  try {
    const { data } = await fetchPatientListAPI();
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 添加就诊人的异步函数
 * */
export const addPatient: AsyncThunk<'添加就诊人成功', Patient, AsyncThunkConfig> = createAsyncThunk('addPatient', async (patientInfo, { rejectWithValue }) => {
  try {
    await addPatientAPI(patientInfo);
    return '添加就诊人成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 查询就诊人详情的异步函数
 * */
export const findPatient: AsyncThunk<Patient, string, AsyncThunkConfig> = createAsyncThunk('findPatient', async (patientId, { rejectWithValue }) => {
  try {
    const { data } = await findPatientAPI(patientId);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 修改就诊人详情的异步函数
 * */
export const updatePatient: AsyncThunk<'编辑就诊人成功', Patient, AsyncThunkConfig> = createAsyncThunk('updatePatient', async (patientInfo, { rejectWithValue }) => {
  try {
    await updatePatientAPI(patientInfo);
    return '编辑就诊人成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }

});

/**
 * @description 删除就诊人的异步函数
 * */
export const deletePatient: AsyncThunk<'删除就诊人成功', string, AsyncThunkConfig> = createAsyncThunk('deletePatient', async (patientId, { rejectWithValue }) => {
  try {
    await deletePatientAPI(patientId);
    return '删除就诊人成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const patientStore = createSlice({
  name: 'patientStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchPatientList.fulfilled, (state, action: PayloadAction<Patient[]>) => {
      const { payload } = action;
      state.patientList = payload;
    });
  },
});


export default patientStore.reducer;